package com.zzdx.deployment.system.service.impl;

import com.zzdx.deployment.common.config.Global;
import com.zzdx.deployment.common.constant.Constants;
import com.zzdx.deployment.common.file.CustomProperties;
import com.zzdx.deployment.common.json.JSON;
import com.zzdx.deployment.common.json.JSONObject;
import com.zzdx.deployment.common.utils.StringUtils;
import com.zzdx.deployment.system.domain.People;
import com.zzdx.deployment.system.domain.PrjversionConfig;
import com.zzdx.deployment.system.domain.ProductResource;
import com.zzdx.deployment.system.service.IFileService;
import com.zzdx.deployment.system.service.IPrjversionConfigService;
import com.zzdx.deployment.system.service.IProductResourceService;
import com.zzdx.deployment.system.service.IProductVersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

/**
 * @Description 文件操作实现类
 * @Author Mason
 * @Date 2018/12/25
 **/
@Service
public class FileServiceImpl implements IFileService {
    private static Logger log = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private IProductVersionService productVersionService;
    @Autowired
    private IProductResourceService productResourceService;
    @Autowired
    private IPrjversionConfigService prjversionConfigService;

    @Override
    public void download(String productResourceId, HttpServletResponse response) throws IOException {
        ProductResource productResource = productResourceService.selectProductByRelative(productResourceId);
        String fileRelativePathWithName = productResource.getResourceRelativePath() + Constants.SLASH + productResource.getResourceName();
        String downloadFolder = Global.getDownloadPath();
        // 文件完整路径
        String fileWhole = StringUtils.appendIfMissing(downloadFolder, Constants.SLASH) + fileRelativePathWithName;
        File file = new File(fileWhole);
        OutputStream outp;
        String characterEncoding = "UTF-8";
        String notExistMsg = "文件不存在!";
        if (!file.exists()) {
            response.setContentType("text/html; charset=UTF-8");
            outp = response.getOutputStream();
            outp.write(notExistMsg.getBytes(characterEncoding));
            outp.flush();
            throw new RuntimeException("filepath cannot null");
        } else {
            String fileName = file.getName();
            fileName = new String(fileName.getBytes("GBK"), "ISO8859_1");
            //设置响应头
            response.reset();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            response.setCharacterEncoding("GBK");

            FileInputStream in = null;
            try {
                outp = response.getOutputStream();
                in = new FileInputStream(file);

                byte[] b = new byte[1024];
                int i = 0;

                while ((i = in.read(b)) > 0) {
                    outp.write(b, 0, i);
                }
                outp.flush();

            } catch (Exception e) {
                log.error("download exception", e);
                outp = response.getOutputStream();
                String msg = "文件读取出错!";
                outp.write(msg.getBytes(characterEncoding));
                outp.flush();
                return;
            } finally {
                if (null != in) {
                    in.close();
                    in = null;
                }
            }
        }
    }

    @Override
    public String upload(MultipartFile file, ProductResource productResource, People people) {
        String fileName = getFileName(file);
        String relativePath = productResource.getResourceRelativePath();
        String downloadPath = Global.getDownloadPath();
        downloadPath = StringUtils.appendIfMissing(downloadPath, "/");
        String wholePath = downloadPath + relativePath + "/" + fileName;
        //填充resource内容
        productResource.setResourceName(fileName);
        //productResource.setResourceRelativePath(relativePath);
        // 存储的文件
        File destFile = new File(wholePath);
        String uploadResult = uploadFile(file, destFile);
        if (Constants.BOOLEAN_STRING_TRUE.equals(uploadResult)) {
            //插入资源记录
            int updateRows = productResourceService.insertProductResource(productResource);
            return updateRows > 0 ? wholePath : Constants.BOOLEAN_STRING_FALSE;
        }

        return Constants.BOOLEAN_STRING_FALSE;
    }

    /**
     * 上传文件并更新资源信息
     *
     * @param file            上传的文件
     * @param productResource 资源对象
     * @return
     */
    @Override
    public String updateAndUpload(MultipartFile file, ProductResource productResource) {
        String fileName = getFileName(file);
//        String relativePath = getRelativePath(productResource);
//        String downloadPath = Global.getDownloadPath();
//        downloadPath = StringUtils.appendIfMissing(downloadPath, "/");
//        String wholePath = downloadPath + relativePath + "/" + fileName;
//        //填充resource内容
//        productResource.setResourceName(fileName);
//        productResource.setResourceRelativePath(relativePath);
//        //有文件则进行上传
//        if (!file.isEmpty()) {
//            // 存储的文件
//            File destFile = new File(wholePath);
//            String uploadResult = uploadFile(file, destFile);
//            if (Constants.BOOLEAN_STRING_TRUE.equals(uploadResult)) {
//                //插入资源记录
//                int updateRows = productResourceService.updateProductResource(productResource);
//                return updateRows > 0 ? Constants.BOOLEAN_STRING_TRUE : Constants.BOOLEAN_STRING_FALSE;
//            }
//        } else {
//            //插入资源记录
//            int updateRows = productResourceService.updateProductResource(productResource);
//            return updateRows > 0 ? Constants.BOOLEAN_STRING_TRUE : Constants.BOOLEAN_STRING_FALSE;
//        }

        return Constants.BOOLEAN_STRING_FALSE;
    }

    @Override
    public String downloadPropFile(String prjvConfigId, HttpServletResponse response) {
        PrjversionConfig prjversionConfig = prjversionConfigService.selectPrjversionConfigById(Integer.parseInt(prjvConfigId));
        String configStr = prjversionConfig.getConfig();
        try {
            JSONObject[] jsonObject = JSON.unmarshal(configStr, JSONObject[].class);
            CustomProperties properties = new CustomProperties();
            for(int i=0 ; i < jsonObject.length ; i++){
                JSONObject jObject = jsonObject[i];
                String name = jObject.getStr("name");
                String value = jObject.getStr("value");
                properties.setProperty(name,value);
            }
            //设置响应头
            String fileName = "custom_config.properties";
            response.reset();
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("GBK");
            properties.store(response.getOutputStream(),"配置平台生成的配置文件");

            return Constants.BOOLEAN_STRING_TRUE;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Constants.BOOLEAN_STRING_FALSE;
    }

    /**
     * 上传文件
     *
     * @param file     上传的文件
     * @param destFile 存储的目标文件
     */
    public String uploadFile(MultipartFile file, File destFile) {
        if (file.isEmpty()) {
            return "false";
        }
        //判断文件父目录是否存在
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        log.info("upload file: " + destFile.getAbsolutePath());

        try {
            file.transferTo(destFile);
            log.info("上传成功");
            return "true";
        } catch (IOException e) {
            log.error(e.toString(), e);
        }

        return "false";
    }

    /**
     *  根据上传的文件获取文件名称
     * @param file 上传的文件
     * @return
     */
    public String getFileName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        log.info("found upload field " + originalFilename);
        return originalFilename;
    }

    /**
     * 根据上传的内容信息，获取文件存储相对路径d
     * @param productResource 资源信息对象
     * @return
     */
    public String getRelativePath(ProductResource productResource,People people) {
//        Integer productVersionId = productResource.getProductVersionId();
//        String resourceType = productResource.getResourceType();
//        String systemType = productResource.getSystemType();
//        String version = productResource.getVersion();
//        String isIncrement = productResource.getIsIncrement();
        //0或1转为full或increment
//        String increName = (StringUtils.isEmpty(isIncrement) || isIncrement.equals(Constants.SUCCESS)) ? "full" : "increment";
//        ProductVersion productVersion = productVersionService.selectProductVersionById(productVersionId);
//        String productCode = productVersion.getProduct().getCode();
        String peopleName = people.getPeopleName();
        //根据信息生成对应目录，如"dorcst/1.0.0/env/full/linux"
        String relativePath = peopleName;
        log.info("upload relative path: " + relativePath);
        return relativePath;
    }

//    public String uploadFile(MultipartFile file, ProductResource productResource, boolean isInsert) {
//
//        Integer productVersionId = productResource.getProductVersionId();
//        String resourceType = productResource.getResourceType();
//        String systemType = productResource.getSystemType();
//        String version = productResource.getVersion();
//        String isIncrement = productResource.getIsIncrement();
//        //0或1转为full或increment
//        String increName = (StringUtils.isEmpty(isIncrement) || isIncrement.equals(Constants.SUCCESS)) ? "full" : "increment";
//        ProductVersion productVersion = productVersionService.selectProductVersionById(productVersionId);
//        String productCode = productVersion.getProduct().getCode();
//
//        //文件名称
//        String clientFileName = file.getOriginalFilename();
//        log.info("found upload field " + clientFileName);
//
//        // 上传路径
//        String downloadPath = Global.getDownloadPath();
//        downloadPath = StringUtils.appendIfMissing(downloadPath, "/", "/");
//        //根据信息生成对应目录，如"dorcst/1.0.0/env/full/linux"
//        String relativePath = productCode + "/" + version + "/" + resourceType + "/" + increName;
//        if (StringUtils.isNotEmpty(systemType)) {
//            relativePath = relativePath + "/" + systemType;
//        }
//        // 上传目录全路径
//        String wholePath = downloadPath + relativePath + "/" + clientFileName;
//        // 存储的文件
//        File destFile = new File(wholePath);
//        //判断文件父目录是否存在
//        if (!destFile.getParentFile().exists()) {
//            destFile.getParentFile().mkdirs();
//        }
//        log.info("upload file: " + wholePath);
//
//        try {
//            file.transferTo(destFile);
//            log.info("上传成功");
//
//            //填充resource内容
//            productResource.setResourceName(clientFileName);
//            productResource.setResourceRelativePath(relativePath);
//            int updateRows;
//            if (isInsert) {
//                //插入资源记录
//                updateRows = productResourceService.insertProductResource(productResource);
//            } else {
//                //更新资源记录
//                updateRows = productResourceService.updateProductResource(productResource);
//            }
//            if (updateRows > 0) {
//                return "true";
//            }
//
//        } catch (IOException e) {
//            log.error(e.toString(), e);
//        }
//        return "false";
//    }
}
